﻿using Furion.Localization;
using MhAdmin.Cache;
using MhAdmin.SqlSugar.Extension;
using Newtonsoft.Json;
using System.Xml.Linq;

namespace MhAdmin.System;

public class UserConfigService : DbRepository<SysUserConfig>, IUserConfigService
{
    private readonly ISimpleCacheService _simpleCacheService;

    public UserConfigService(ISimpleCacheService simpleCacheService)
    {
        _simpleCacheService = simpleCacheService;
    }

    #region 查询

    public async Task<List<UserColumnConfigOutput>> GetColumnConfig(QueryUserColumnConfigInput input)
    {
        // 账户名称
        string? user = (App.User.FindFirst(ClaimConst.Account)?.Value) ?? throw Oops.Bah("未知的请求用户");

        //先从Redis拿 key是固定码+TableId
        var userColumnConfigs = _simpleCacheService.Get<List<UserColumnConfigOutput>>(SystemConst.Cache_UserColumnConfig + input.TableId);
        if (userColumnConfigs == null)
        {
            //Redis 没有就去数据库拿
            userColumnConfigs = await Context.Queryable<SysUserConfig>()
             .Where(x => x.TableId == input.TableId)
             .Where(x => x.CreateUser == user)
             .OrderBy(x => x.Sort)
             .Select(x => new UserColumnConfigOutput
             {
                 Id = x.Id,
                 ColumnId = x.ColumnId,
                 IsShow = x.IsShow,
                 Sort = x.Sort,
                 Width = x.Width,
             })
             .ToListAsync();
            if (userColumnConfigs.Count > 0)
            {
                //插入Redis
                _simpleCacheService.Set(SystemConst.Cache_UserColumnConfig + input.TableId, userColumnConfigs);
            }
        }

        return userColumnConfigs;
    }

    #endregion 查询

    #region 编辑

    public async Task UpdateColumnConfig(List<UpdateUserColumnConfigInput> update)
    {
        if (update.Count == 0) throw Oops.Bah("数据长度不可为0");
        var columnConfig = update.Adapt<List<SysUserConfig>>();//实体转换
        await Console.Out.WriteLineAsync(JsonConvert.SerializeObject(columnConfig));
        if (await InsertOrUpdateAsync(columnConfig))//更新数据
            await RefreshCache(update.First().TableId);//刷新缓存
    }

    #endregion 编辑

    #region 删除

    public async Task DeleteColumnConfig(List<BaseIdInput> input)
    {
        var ids = input.Select(it => it.Id).ToList();
        if (ids.Count > 0)
        {
            // 查询出所有的TableId
            var tableId = Context.Queryable<SysUserConfig>().Where(x => ids.Contains(x.Id)).Select(x => x.TableId).ToList().Distinct();

            if (await Context.FalseDeleteChangeAsync<SysUserConfig>(ids))
                await RefreshCache(tableId);//刷新缓存
        }
    }

    #endregion 删除

    #region 方法

    public async Task RefreshCache(IEnumerable<string> tableId)
    {
        foreach (var item in tableId)
        {
            await RefreshCache(item);
        }
    }

    public async Task RefreshCache(string tableId)
    {
        _simpleCacheService.Remove(SystemConst.Cache_UserColumnConfig + tableId);//从redis删除
        await GetColumnConfig(new QueryUserColumnConfigInput() { TableId = tableId });
    }

    #endregion 方法
}
